package com.yksj.healthtalk.ui.friend;

import java.util.ArrayList;

import org.handmark.pulltorefresh.library.PullToRefreshBase;
import org.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import org.handmark.pulltorefresh.library.PullToRefreshListView;

import sfs2x.client.core.SFSEvent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

import com.yksj.healthtalk.adapter.FriendAdapter;
import com.yksj.healthtalk.adapter.FriendAdapter.onClickFriendAttentionListener;
import com.yksj.healthtalk.adapter.FriendAdapter.onClickFriendHeadListener;
import com.yksj.healthtalk.comm.BaseFragmentActivity;
import com.yksj.healthtalk.comm.LodingFragmentDialog;
import com.yksj.healthtalk.entity.CustomerInfoEntity;
import com.yksj.healthtalk.net.http.HttpRestClient;
import com.yksj.healthtalk.net.http.ObjectHttpResponseHandler;
import com.yksj.healthtalk.net.socket.SmartFoxClient;
import com.yksj.healthtalk.services.MessagePushService;
import com.yksj.healthtalk.ui.R;
import com.yksj.healthtalk.ui.app.AppData;
import com.yksj.healthtalk.ui.app.HTalkApplication;
import com.yksj.healthtalk.ui.setting.PersonalInformationActivity;
import com.yksj.healthtalk.utils.FriendHttpUtil;
import com.yksj.healthtalk.utils.FriendUtil;
import com.yksj.healthtalk.utils.ToastUtil;

/**
 * 关注我的 (我的粉丝)
 * 
 * @author root
 * 
 */
public class FriendFansActivity extends BaseFragmentActivity implements
		OnClickListener, OnItemClickListener, OnRefreshListener2<ListView>,onClickFriendAttentionListener, onClickFriendHeadListener{

	private View mTitleBack;
	private PullToRefreshListView mPullToRefreshListView;
	private TextView mTitleName;
	private ListView mListView;
	private int pagenum = 20;
	private int pagesize = 1;
	private ArrayList<CustomerInfoEntity> infoEntities;
	private ArrayList<String> ids;
	private FriendAdapter adapter;
	protected AppData mAppData;
	private CustomerInfoEntity cacheCustomerInfoEntity;
	private BroadcastReceiver receiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			String action = intent.getAction();
			if (action.equals(MessagePushService.ACTION_COLLECT_FRIEND)) {
				
				LodingFragmentDialog.dismiss(getSupportFragmentManager());
				String result = intent.getStringExtra("result");
				if (result.equals("0")) {
					ToastUtil.showShort(getApplicationContext(), R.string.groupNewFail);
				} else if (result.equals("-1")) {
					ToastUtil.showShort(getApplicationContext(),R.string.against__blacklist_operations);
				} else {
					FriendHttpUtil.requestAttentionTofriendsResult(FriendFansActivity.this, cacheCustomerInfoEntity, mAppData);
					adapter.notifyDataSetChanged();
				}
				
			} else if (action.equals(MessagePushService.ACTION_MESSAGE)) {
				if (intent.hasExtra("senderId")) {
					adapter.notifyDataSetChanged();
				}
			}
		}

	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.friend_exact_search);

		initWidget();
		initClickListener();
		initData();
		getMyFans(SmartFoxClient.getLoginUserId(), String.valueOf(pagenum),
				String.valueOf(pagesize));
	}

	private void getMyFans(String userid, String pagenum, final String pagesize) {
		HttpRestClient.doHttpFindMyFriends(userid, pagenum, pagesize,
				new ObjectHttpResponseHandler() {
					@Override
					public Object onParseResponse(String content) {
						return FriendHttpUtil.jsonAnalysisFriendEntity(content,
								true);
					}
					@Override
					public void onSuccess(int statusCode, Object response) {
						if (response != null && response instanceof ArrayList) {
							ArrayList<CustomerInfoEntity> entities = (ArrayList<CustomerInfoEntity>) response;
							if (entities.size() == 0) {
								ToastUtil.showToastPanl(
										getString(R.string.no_more_data));
							} else {
								if (pagesize.equals("1")) {
									infoEntities.clear();
								}
								infoEntities.addAll(entities);
								adapter.notifyDataSetChanged();
							}
						} else {
							ToastUtil.showShort(getApplicationContext(),R.string.requst_error);
						}
						super.onSuccess(statusCode, response);
					}

					@Override
					public void onFinish() {
						mPullToRefreshListView.onRefreshComplete();
						super.onFinish();
					}
				});
	}

	private void initData() {
		mAppData = HTalkApplication.getAppData();
		mTitleName.setText("关注我的人");
		infoEntities = new ArrayList<CustomerInfoEntity>();
		ids = new ArrayList<String>();
		adapter = new FriendAdapter(this, infoEntities);
		adapter.setonClickFriendAttentionListener(this);
		adapter.setonClickFriendHeadListener(this);
//		adapter.setType(0);
		mListView.addFooterView(LayoutInflater.from(getApplicationContext())
				.inflate(R.layout.list_line_layout, null));
		mListView.setOnItemClickListener(this);
		mListView.setAdapter(adapter);
	}

	private void initClickListener() {
		mTitleBack.setOnClickListener(this);
		mPullToRefreshListView.setOnRefreshListener(this);
	}

	private void initWidget() {
		mPullToRefreshListView = (PullToRefreshListView) findViewById(R.id.hall);
		mTitleBack = (Button) findViewById(R.id.title_back);
		mTitleName = (TextView) findViewById(R.id.title_lable);
		mListView = mPullToRefreshListView.getRefreshableView();
	}

	@Override
	public void onClick(View v) {
		if (v.getTag() != null && v.getTag() instanceof Integer) {
			int position = (Integer) v.getTag();
			Intent intent;
			if (!FriendUtil.isDoctor(infoEntities.get(position))) {
				intent = new Intent();
				intent.setClass(this, FriendInformUI.class);
				intent.putExtra("id", infoEntities.get(position).getId());
				startActivity(intent);
			} else {
				 intent = new Intent(this, DoctorMainActivity.class);
				intent.putExtra("id", infoEntities.get(position).getId());
				startActivity(intent);
			}
		} else {
			switch (v.getId()) {
			case R.id.title_back:
				finish();
				break;
			}
		}
	}

	@Override
	protected void onStart() {
		if (adapter != null) {
			adapter.notifyDataSetChanged();
		}
		IntentFilter filter = new IntentFilter();
		filter.addAction(MessagePushService.ACTION_MESSAGE);
		filter.addAction(MessagePushService.ACTION_COLLECT_FRIEND);
		filter.addAction(SFSEvent.CONNECTION_LOST);
		registerReceiver(receiver, filter);
		super.onStart();
	}

	@Override
	protected void onStop() {
		unregisterReceiver(receiver);
		super.onStop();
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		if (1 <= position && position <=  infoEntities.size()) {
			FriendHttpUtil.onItemClick(this, infoEntities.get(position - 1));
		}
	}

	@Override
	public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
		// TODO Auto-generated method stub
		pagenum = 20;
		pagesize = 1;
		getMyFans(SmartFoxClient.getLoginUserId(), String.valueOf(pagenum),
				String.valueOf(pagesize));
	}

	@Override
	public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
		// TODO Auto-generated method stub
		getMyFans(SmartFoxClient.getLoginUserId(), String.valueOf(pagenum),
				String.valueOf(pagesize++));
	}

	@Override
	public void onClickFriendAttention(int attentioned,
			CustomerInfoEntity entity, int positon) {
		cacheCustomerInfoEntity = FriendHttpUtil.requestAttentionTofriends(this, null, entity);		
	}


		@Override
		public void onClickFriendHead(CustomerInfoEntity entity, int positon) {
			if (SmartFoxClient.getLoginUserId().equals(entity.getId())) {
				Intent intent = new Intent();
				intent.setClass(this, PersonalInformationActivity.class);
				startActivity(intent);
			}else {
				Intent intent = new Intent(this, DoctorMainActivity.class);
				intent.putExtra("id", entity.getId());
				startActivity(intent);
			}
		}
	

}